import { useTabViewStoreWithOut } from '@/store/modules/tabView.ts';

export const contextmenuItemView = ref();
export const contextmenuIndex = ref();
export const useTabView = useTabViewStoreWithOut();

export function useTabNavControl() {
  const router = useRouter();

  router.getRoutes().forEach((route: any) => {
    // 添加到页面缓存栈
    if (route.meta && !route.meta.noCache && route.name) {
      useTabView.addCacheView(route);
    }
    // 添加到固定页面栈
    if (route.meta && route.meta.affix) {
      useTabView.addFixedView(route);
    }
  });

  const reloadPage = () => {
    router.go(0);
  };

  const closeCurrentPage = (path?: string) => {
    if (path) {
      let flag = false;
      useTabView.getTabViews.forEach((route, index) => {
        if (route.path === path) {
          contextmenuIndex.value = index;
          flag = true;
        }
      });
      if (flag) {
        closeCurrentPage();
      } else {
        throw Error('未找到需要关闭的tab路由' + path);
      }
    } else {
      // 在RXnav组件中直接调用的关闭标签的方法
      useTabView.closeTabView(contextmenuIndex.value);
      router.push(
        useTabView.getTabViews[contextmenuIndex.value - 1 > 0 ? contextmenuIndex.value - 1 : 0],
      );
    }
  };

  const closeLeftPage = () => {
    for (let i = contextmenuIndex.value - 1; i > 0; i--) {
      useTabView.closeTabView(i);
    }
    router.push(useTabView.getTabViews[1]);
  };

  const closeOtherPage = () => {
    for (let i = useTabView.getTabViews.length - 1; i > 0; i--) {
      if (i !== contextmenuIndex.value) {
        useTabView.closeTabView(i);
      }
    }
    router.push(useTabView.getTabViews[1]);
  };

  const closeRightPage = () => {
    for (let i = useTabView.getTabViews.length - 1; i > contextmenuIndex.value; i--) {
      useTabView.closeTabView(i);
    }
    router.push(useTabView.getTabViews[contextmenuIndex.value]);
  };

  const closeAllPage = () => {
    for (let i = useTabView.getTabViews.length - 1; i > 0; i--) {
      useTabView.closeTabView(i);
    }
    router.push(useTabView.getTabViews[0]);
  };

  return {
    reloadPage,
    closeAllPage,
    closeCurrentPage,
    closeLeftPage,
    closeRightPage,
    closeOtherPage,
  };
}
